package thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author weim
 * @date 18-8-29
 */
public class MyLock {

    private static Integer index = 0;

    private static Lock lock = new ReentrantLock();

    private static Lock tryLock = new ReentrantLock();

    private static ReadWriteLock writeReadLock = new ReentrantReadWriteLock();

    public static void main(String[] args) {

//        for(int i=0; i<10; i++) {
//            new Thread(() -> {
//                count(Thread.currentThread().getName());
//
//            }).start();
//        }
//
//        System.out.println("aaaaaaaaaaaaaaaa");


        index = 10;
        for(int i=0; i<10; i++) {
            new Thread(() -> {
                sub(Thread.currentThread().getName());

            }).start();
        }

        System.out.println("bbbbbbbbbbbbbbbb");

    }

    private static void count(String name) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        lock.lock();
        index ++ ;
        System.out.println(name + "  : " + index);
        lock.unlock();
    }

    private static void sub(String name) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        boolean b = tryLock.tryLock();

//        boolean b = false;
//        try {
//             b = tryLock.tryLock(100, TimeUnit.MICROSECONDS);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        if(b) {
            index -- ;
            System.out.println(name + "  : " + index);

            tryLock.unlock();
        } else {
            System.out.println(name + "  error ");
        }
    }


    public void test(ReadWriteLock writeReadLock) {
        //多个线程可以同时进行读操作，这样就大大提升了读操作的效率。
        // 不过要注意的是，如果有一个线程已经占用了读锁，则此时其他线程如果要申请写锁，则申请写锁的线程会一直等待释放读锁。
        // 如果有一个线程已经占用了写锁，则此时其他线程如果申请写锁或者读锁，则申请的线程也会一直等待释放写锁。
        writeReadLock.readLock().lock();
        writeReadLock.writeLock().lock();
        writeReadLock.readLock().unlock();
        writeReadLock.writeLock().unlock();
    }




}